package controllers

import (
	"findme-api/models"
	"fmt"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	"math/rand"
	"strconv"
	"strings"
	"time"
)

type UserController struct {
	beego.Controller
}

type User struct {
	Id string `json:"id"`
	Uid string `json:"uid"`
	Username string `json:"username"`
	Usertype string `json:"usertype"`
	Company string `json:"company"`
	Department string `json:"department"`
}

type UJSONS struct {
	//必须的大写开头
	Error_code int `json:"error_code"`
	Total int `json:"total"`
	Alldepartment []Department `json:"alldepartment"`
	Allarea []Area `json:"allarea"`
	DATA []User  `json:"data"`
}


//func (c *UserController) userAllowCross() {
//	c.Ctx.ResponseWriter.Header().Set("Access-Control-Allow-Origin", "http://localhost:14000")       //允许访问源
//	c.Ctx.ResponseWriter.Header().Set("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS")    //允许post访问
//	c.Ctx.ResponseWriter.Header().Set("Access-Control-Allow-Headers", "Content-Type,Authorization") //header的类型
//	c.Ctx.ResponseWriter.Header().Set("Access-Control-Max-Age", "1728000")
//	c.Ctx.ResponseWriter.Header().Set("Access-Control-Allow-Credentials", "true")
//	c.Ctx.ResponseWriter.Header().Set("content-type", "application/json") //返回数据格式是json
//}


//用户登录接口
func (this *UserController) Login() {
	FileLogs.Info("==================用户登录================")
	//fmt.Println(beego.AppConfig.String("mysqlurls"))

	//this.userAllowCross() //允许跨域
	//this.Ctx.ResponseWriter.Header().Set("Access-Control-Allow-Origin", this.Ctx.Request.Header.Get("Origin"))
	 body := this.Ctx.Input.RequestBody //这是获取到的json二进制数据
	 userinfoarray := Getinfofromjson(string(body))
	 fmt.Println(userinfoarray)

	type Data struct {
		Token   string `json:"token"`
	}

	type JSON struct {
		//必须的大写开头
		Error_code int `json:"error_code"`
		Data Data `json:"data"`
	}

	o := orm.NewOrm()
	var userrows []models.UserInfo
	if _, err := o.Raw("SELECT * FROM user_info WHERE username = ?  ",userinfoarray[0]).QueryRows(&userrows); err != nil {
		fmt.Println("err")
	}

	flag := false
	role := "null"
	portraiturl := "null"
	//查找登录用户名
	for _,userrow := range userrows{
		fmt.Println("userrow :",userrow)
		fmt.Println("找到登录用户名")
		if userrow.Password == userinfoarray[1] {
			flag = true
			role = userrow.Usertype
			if role == "superuser" {
				portraiturl = "http://192.168.1.109:19001/static/img/superuser.jpg"
			}else {
				portraiturl = "http://192.168.1.109:19001/static/img/user.png"
			}
			break
		}else {
			fmt.Println("密码错误")
			//密码错误
			data := &JSON{2,Data{"null"}}
			this.Data["json"] = data
			this.ServeJSON()
		}
	}
	timestamp := 1513580645
	//注意这个参数暂时用不到
	temppara := time.Unix(int64(timestamp),0)
	company := models.QueryCompanyByUsername(userinfoarray[0])
	coordinate := models.Getcoordinate(company)
	// 生成token
	token,_ := CreateToken(userinfoarray[0],role, company,portraiturl,coordinate,temppara)

	if flag == false {
		FileLogs.Info("用户不存在")
      //该用户不存在
		data := &JSON{1,Data{Token:token}}
		this.Data["json"] = data
		this.ServeJSON()
	}else {
		FileLogs.Info("登录成功")
		//登录成功
		data := &JSON{0,Data{Token:token}}
		this.Data["json"] = data
		this.ServeJSON()
	}
}


//注册超级用户接口
func (this *UserController)Registersuper(){
	FileLogs.Info("===注册超级用户接口===")
	//this.userAllowCross()
	supername := this.GetString("supername")
	supercode := this.GetString("supercode")
	companyname := this.GetString("companyname")

	type DATA struct {
		Comoanyname string
	}

	type JSONS struct {
		//必须的大写开头
		Error_code int
		DATA DATA
	}
	//检查超级用户注册码
	if supercode == "askme12345678" {
	var companyrows []models.CompanyInfo
	o := orm.NewOrm()
	if _, err := o.Raw("SELECT * FROM company_info WHERE companyname = ?  ",companyname).QueryRows(&companyrows); err != nil {
		FileLogs.Info("err")
	}
	flag := false
	//如果能查到，说明公司存在
	for _,companyrow := range companyrows{
		FileLogs.Info("companyrow :",companyrow)
		flag = true
		break
	}

	if flag == false{
		//该公司不存在，请先注册超级用户所在公司
		data := &JSONS{2,DATA{supername}}
		this.Data["json"] = data
		this.ServeJSON()
	}else {
        var userrows []models.UserInfo
		if _, err := o.Raw("SELECT * FROM user_info WHERE username = ?  ",supername).QueryRows(&userrows); err != nil {
			FileLogs.Info("err")
		}
		userflag := false
		//如果能查到，则该用户名已经被注册
		for _,userrow := range userrows{
			FileLogs.Info("userrow :",userrow)
			FileLogs.Info("该用户名已存在，请重新注册")
			userflag = true
			break
		}

		//fmt.Println("userflag:",userflag)

		if userflag == true{
			//用户名已经存在
			data := &JSONS{3,DATA{supername}}
			this.Data["json"] = data
			this.ServeJSON()
		}else {

			//成功注册
			//uuid := uuid.NewV4()

			//uuid := uuid.Must(uuid.NewV4())

			timeUnix := strconv.FormatInt(time.Now().Unix(), 10)
			rand.Seed(time.Now().Unix())
			randnum :=rand.Intn(1000000)
			fmt.Println(timeUnix+strconv.Itoa(randnum))

			timeStr := time.Now().Format("2006-01-02 15:04:05")

			userdata := models.UserInfo{Uid:"sdfsdf",
					Username: supername,
					Password: "123456",
					Usertype: "superuser",
					Regtime: timeStr,
					Timestamp: timeUnix,
					Company: companyname,
					Department: "all",
					Add: "0",
					Delete: "0",
					Change: "0",
					Querycap: "0",
				}
			id, _ := models.AddUser(&userdata)
			fmt.Println(id)

			data := &JSONS{0, DATA{supername}}
			this.Data["json"] = data
			this.ServeJSON()
		}
	}
	}else {
		//注册码错误
		data := &JSONS{1,DATA{supername}}
		this.Data["json"] = data
		this.ServeJSON()
	}
}

//注册普通用户
func (this *UserController)Registeruser()  {
	FileLogs.Info("===注册普通用户===")
	//this.userAllowCross()
	token := this.Ctx.Request.Header.Get("Authorization")
	tokenjson := ParseToken(token)
	supername := Getusernamefromjsoninfo(tokenjson)
	//username := this.GetString("username")
	//superword := this.GetString("superword")
    //password := this.GetString("password")
	//department := this.GetString("department")
	//add := this.GetString("add")
	//delete := this.GetString("delete")
	//change := this.GetString("change")
	//querycap := this.GetString("querycap")



	body := this.Ctx.Input.RequestBody //这是获取到的json二进制数据
	//fmt.Println(string(body))
	userarray := Getinfofromjson(string(body))
	username := userarray[0]
	superword := userarray[1]
	password := userarray[2]
	department := userarray[3]
	add := userarray[4]
	delete := userarray[5]
	change := userarray[6]
	querycap := userarray[7]


	type DATA struct {
		Username string `json:"username"`
	}
	type JSONS struct {
		//必须的大写开头
		Error_code int `json:"error_code"`
		DATA DATA `json:"data"`
	}

	o := orm.NewOrm()
	var userrows []models.UserInfo
	if _, err := o.Raw("SELECT * FROM user_info WHERE username = ?  ",username).QueryRows(&userrows); err != nil {
		fmt.Println("err")
	}

	userflag := false
	//如果能查到，则该用户名已经被注册
	for _,userrow := range userrows{
		fmt.Println("userrow :",userrow)
		fmt.Println("该用户名已存在，请重新注册")
		userflag = true
		break
	}
	if userflag ==true {
		//该用户名已经被注册
		data := &JSONS{1,DATA{username}}
		this.Data["json"] = data
		this.ServeJSON()
	}else {
		var userrows []models.UserInfo
		if _, err := o.Raw("SELECT * FROM user_info WHERE username = ?  ",supername).QueryRows(&userrows); err != nil {
			FileLogs.Info("err")
		}
		company := ""
		superword1 := ""
		for _,userrow := range userrows{
			//fmt.Println("company :",userrow.Company)
				company = userrow.Company
			    superword1 = userrow.Password
		}
		if superword == superword1 {
			//注册成功
			//uuid, _ := uuid.NewV4()


			timeUnix := strconv.FormatInt(time.Now().Unix(), 10)
			rand.Seed(time.Now().Unix())
			randnum :=rand.Intn(1000000)
			//fmt.Println(timeUnix+strconv.Itoa(randnum))
			timeStr := time.Now().Format("2006-01-02 15:04:05")
			//fmt.Println(timeStr)
			//fmt.Println("password:",password)
			userdata := models.UserInfo{Uid: timeUnix+strconv.Itoa(randnum),
				Username:   username,
				Password:   password,
				Usertype:   "user",
				Regtime:    timeStr,
				Timestamp:  timeUnix,
				Company:    company,
				Department: department,
				Add:        add,
				Delete:     delete,
				Change:     change,
				Querycap:   querycap,
			}
			id, _ := models.AddUser(&userdata)
			fmt.Println(id)

			data := &JSONS{0, DATA{username}}
			this.Data["json"] = data
			this.ServeJSON()
		}else {
			//超级用户密码错误
			data := &JSONS{2, DATA{username}}
			this.Data["json"] = data
			this.ServeJSON()
		}
	}
}

//显示所有账户信息，只有超级账户有这个权限
func (this *UserController) ShowalluserInfo() {
	FileLogs.Info("===显示所有账户信息，只有超级账户有这个权限===")
	//this.userAllowCross()
	token := this.Ctx.Request.Header.Get("Authorization")
	company := GetCompanyfromToken(token)
	tokeninfo := ParseToken(token)
	username := Getusernamefromjsoninfo(tokeninfo)
	page := this.GetString("page")
	size := this.GetString("size")
	userDataChan := make(chan string, 1000)
	totalItem := models.Showalluser(userDataChan,username,page,size)
	userdata := []User{}
	tempdata := User{"","","","","",""}

	departments := models.Getalldepartment(company)
	areas := models.Getallareas(company)

	departmentt := []Department{}
	departsegs := strings.Split(departments, "，")
	for _,item := range departsegs{
		//fmt.Println(item)
		departmentt = append(departmentt,Department{item})
	}

	areaa := []Area{}
	areasegs := strings.Split(areas, "，")
	for _,item := range areasegs{
		areaa = append(areaa,Area{item})
	}


	//遍历信道，读取数据
	var i int = 0
	var lenuserdatachan = len(userDataChan)
	if lenuserdatachan != 0 {
		for item := range userDataChan{
			//fmt.Println("get data from database:",item)
			//m[strconv.Itoa(i)] =item
			itemsegments := strings.Split(item,"and")
			tempdata = User{itemsegments[0],itemsegments[1],itemsegments[2],itemsegments[3],itemsegments[4],itemsegments[5]}
			userdata = append(userdata, tempdata)
			if i == (lenuserdatachan - 1) {
				break
			}
			i++
		}
		data := &UJSONS{0,totalItem,departmentt,areaa,userdata}
		this.Data["json"] = data
		this.ServeJSON()
	}else {
		userdata = append(userdata, tempdata)
		data := &UJSONS{1, totalItem, []Department{},[]Area{},[]User{}}
		this.Data["json"] = data
		this.ServeJSON()
	}
}


//删除用户信息，只有超级用户有此权限
func (this *UserController)DeleteuserInfo(){
	//this.userAllowCross()
	FileLogs.Info("===删除用户===")
	token := this.Ctx.Request.Header.Get("Authorization")
	tokeninfo := ParseToken(token)
	superuser := Getusernamefromjsoninfo(tokeninfo)
	username  := this.GetString("username")
    //fmt.Println(superuser)
	//fmt.Println(username)
	result := models.Deleteuser(superuser,username)
	//fmt.Println(result)
	type JSONS struct {
		//必须的大写开头
		Error_code int
	}
	if result == "success" {
		data := &JSONS{0}
		this.Data["json"] = data
		this.ServeJSON()
	}else {
		data := &JSONS{1}
		this.Data["json"] = data
		this.ServeJSON()
	}
}



//编辑用户信息
func (this *UserController)Edituserinfo(){
	    FileLogs.Info("===编辑用户信息===")
	    //this.userAllowCross()
		token := this.Ctx.Request.Header.Get("Authorization")
		tokeninfo := ParseToken(token)
		superuser := Getusernamefromjsoninfo(tokeninfo)
		company := GetCompanyfromToken(token)
		FileLogs.Info(company)
		//var obs []CapLabel
		body := this.Ctx.Input.RequestBody //这是获取到的json二进制数据
		//fmt.Println(string(body))
		userinfoarray := Getinfofromjson(string(body))
		//fmt.Println(userinfoarray)
		type JSONS struct {
			//必须的大写开头
			Error_code int `json:"error_code"`
		}
	o := orm.NewOrm()

	//检测是否是超级用户
	var userrows []models.UserInfo
	if _, err := o.Raw("SELECT * FROM user_info WHERE username = ?  ",superuser).QueryRows(&userrows); err != nil {
		FileLogs.Info("err")
	}
	usertype := ""
	for _,userrow := range userrows{
		//fmt.Println("company :",userrow.Company)
		usertype = userrow.Usertype
	}
	if  usertype == "superuser" {
		var userrows []models.UserInfo
		//判断提交的用户名和原来的用户名是否相同
		if _, err := o.Raw("SELECT * FROM user_info WHERE uid = ?  ", userinfoarray[1]).QueryRows(&userrows); err != nil {
			FileLogs.Info("err")
		}
		userflag := false
		for _, userrow := range userrows {
			if userrow.Username == userinfoarray[2] {
				userflag = true
			}
			break
		}

		if userflag == true {
			_, err := o.Raw("update user_info set department = ? where uid = ?",
				userinfoarray[5], userinfoarray[1]).Exec()
			if err != nil {
				FileLogs.Info("更新失败！")
				data := &JSONS{1}
				this.Data["json"] = data
				this.ServeJSON()
			}

			data := &JSONS{0}
			this.Data["json"] = data
			this.ServeJSON()
		} else {
			var userrows []models.UserInfo
			if _, err := o.Raw("SELECT * FROM user_info WHERE username = ?  ", userinfoarray[2]).QueryRows(&userrows); err != nil {
				FileLogs.Info("err")
			}
			userflag := false
			//如果能查到，则该用户名已经被注册
			for _, userrow := range userrows {
				FileLogs.Info("userrow :", userrow)
				FileLogs.Info("该用户名已存在，请重新注册")
				userflag = true
				break
			}
			if userflag == true {
				//该用户名已经被注册,不能修改成这个用户名
				data := &JSONS{2}
				this.Data["json"] = data
				this.ServeJSON()
			} else {
				//根据uuid修改用户名
				_, err := o.Raw("update user_info set  username= ?, department = ? where uid = ?",
					userinfoarray[2], userinfoarray[5], userinfoarray[1]).Exec()
				if err != nil {
					FileLogs.Info("更新失败！")
					data := &JSONS{1}
					this.Data["json"] = data
					this.ServeJSON()
				}
				data := &JSONS{0}
				this.Data["json"] = data
				this.ServeJSON()
			}
		}
		} else {
			//不是超级用户
			data := &JSONS{3}
			this.Data["json"] = data
			this.ServeJSON()
		}
}